<template>
  <div>
    <!-- 更新进度弹出框 -->
    <CommonDialog
      title="评论"
      width="75%"
      v-bind:dialogVisible="updateDialogVisible"
      @on-change-dialogVisible="updateChange"
      class="update"
      top="10vh"
    >
      <template #body>
        <el-form class="updateForm" :model="updateForm" label-position="top" ref="updateForm">
          <!-- <el-row :gutter="20" type="flex" v-if="isShow">
            <el-col :span="8">
              <el-form-item
                label="当前阶段"
                class="nowStage"
                prop="nowStage"
                :rules="[
                  {
                    required: true,
                    message: '请选择当前阶段',
                    trigger: 'select'
                  }
                ]"
              >
                <el-select
                  v-model="updateForm.nowStage"
                  placeholder="请选择当前阶段"
                  clearable
                  filterable
                  @change="onProduction"
                >
                  <el-option v-for="(item, index) in childStageList" :key="index" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="指派人"
                class="nowStage"
                prop="carbonPerson"
                :rules="[
                  {
                    required: true,
                    message: '请选择指派人',
                    trigger: 'select'
                  }
                ]"
              >
                <el-select
                  v-model="updateForm.carbonPerson"
                  placeholder="请选择指派人"
                  clearable
                  filterable
                  @change="carbonPersonChange"
                >
                  <el-option v-for="(item, index) in updateUserList" :key="index" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="部门" class="nowStage">
                <el-input v-model="updateForm.department" disabled> </el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="评论"
                class="updateReason"
                prop="nowPlaint"
                :rules="[
                  {
                    required: true,
                    message: '请输入评论',
                    trigger: 'change'
                  }
                ]"
              >
                <!-- <vue-tinymce
                  v-model="updateForm.nowPlaint"
                  :setting="setting"
                /> -->
                <socialUpload :contentDefault="updateForm.nowPlaint" @getContent="getUpdateContent"></socialUpload>
                <!-- <quill-editor v-model="updateForm.nowPlaint"
                              ref="updateReasonEditor"> </quill-editor> -->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="添加附件" class="uploadFiles">
                <el-upload
                  class="upload-demo"
                  :action="fileUpload"
                  :on-success="onFileSuccess"
                  :on-error="onFileError"
                  :on-remove="onFileRemove"
                  :on-preview="handlePreview"
                  :data="{
                    checkOfficeFmt: false,
                    isTmp: false
                  }"
                  multiple
                  :limit="3"
                  :file-list="encLosureList"
                >
                  <el-button size="small" type="primary" style="margin-top: 6px">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #dialog_footer>
        <el-button class="submitCancel" @click="updateCancel">取 消</el-button>
        <el-button type="primary" @click="confirmUpdate('updateForm')" class="submitReme">发布</el-button>
      </template>
    </CommonDialog>
  </div>
</template>

<script>
import socialUpload from '../socialUpload/socialUpload.vue'
import CommonDialog from '@/components/commonDialog/commonDialog.vue'
import { FeedBack } from '@/api/feedBack/server'
export default {
    name: '',
    components: {
        CommonDialog,
        socialUpload
    },
    props: {},
    data() {
        return {
            // 文件上传列表
            encLosureList: [],
            // 文件上传地址
            fileUpload: `${process.env.VUE_APP_GOLDWIND_BASE_API}/v2/file/upload`,
            // 弹出框
            updateDialogVisible: false,
            // 阶段列表
            childStageList: [],
            isShow: false,
            // 指派人列表
            updateUserList: [],
            // 当前人员信息
            userInfo: {},
            // 详情ID
            tableItemsID: '',
            // 传入的指派人ID
            userID: '',
            // 传入的阶段ID
            stageID: '',
            // 更新进度
            updateForm: {
                nowStage: '',
                carbonPerson: '',
                nowPlaint: '',
                department: ''
            },
            setting: {
                branding: false,
                menubar: false,
                toolbar:
          'undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |',
                toolbar_drawer: 'sliding',
                quickbars_selection_toolbar:
          'removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor',
                plugins: 'link image  table lists fullscreen',
                language: 'zh_CN',
                init_instance_callback: editor => {
                    if (this.content) {
                        editor.setContent(this.content)
                    }
                    this.finishInit = true
                    editor.on('NodeChange Change SetContent KeyUp', () => {
                        this.hasChanged = true
                    })
                }, // 上传图片
                convert_urls: false,
                automatic_uploads: true, // 开启点击图片上传时，自动进行远程上传操作
                images_upload_base_path: `${process.env.VUE_APP_GOLDWIND_BASE_API}`, // 图片上传的基本路径
                images_upload_url: '/v2/file/upload',
                images_upload_handler: (blobInfo, success, failure) => {
                    var xhr, formData

                    xhr = new XMLHttpRequest()
                    xhr.withCredentials = false
                    xhr.open('POST', `${process.env.VUE_APP_GOLDWIND_BASE_API}` + '/v2/file/upload')
                    xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token)
                    // xhr.setRequestHeader('token', JSON.parse(sessionStorage.getItem('USERINFO')).token);

                    formData = new FormData()
                    formData.append('file', blobInfo.blob())

                    formData.append('checkOfficeFmt', false)
                    formData.append('isTmp', false)
                    xhr.onload = function(e) {
                        var json
                        console.log(e, xhr)
                        console.log(this)

                        if (xhr.errcode == '0') {
                            failure('服务器错误:' + xhr.msg)
                            return
                        }
                        json = JSON.parse(this.responseText)
                        if (!json.data || typeof json.data.fileSourceId != 'string') {
                            failure('服务器错误')
                            return
                        }
                        success(
                            `${process.env.VUE_APP_GOLDWIND_BASE_API}` +
                '/v2/file/download?' +
                '&fileSourceId=' +
                json.data.fileSourceId
                        )
                    }
                    xhr.send(formData)
                },
                image_advtab: false,
                language_url: 'tinymce/langs/zh_CN.js', // 语言包的路径
                elementpath: false, // 隐藏元素路径，不明白的可以切换true/false观察页面
                statusbar: false,
                resize: false,
                height: 200
            }
        }
    },
    computed: {},
    watch: {},
    created() {},
    mounted() {},
    methods: {
    /**
     * @description: 弹出框加载方法
     * @param {String} string 详情信息
     * @param {String} _stageID 阶段ID
     * @param {String} trueID 详情ID
     */
        show(string, _stageID, trueID) {
            this.encLosureList = []
            this.stageID = _stageID
            this.getChildStageList()
            const row = JSON.parse(string)
            console.log('row', row)
            this.productId = row.productId
            // 产品名称选择器 (选择改变指派人)
            this.updateProductionChange(this.productId)
            this.updateDialogVisible = true
            // this.updateForm.carbonPerson = row.userId
            this.getuserId(row, _stageID, trueID)
        },
        async getuserId(row, _stageID, trueID) {
            try {
                const result = await FeedBack.UserGetUserInfoAsync()
                if (result.success) {
                    console.log('获取当前账号信息', result.data)

                    this.updateRow(row, _stageID, trueID, result.data.id)
                } else {
                    this.updateRow(row, _stageID, trueID, '')
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 上传成功
     * @param {Object} _response 成功返回结果
     * @param {Object} _file 上传的文件
     * @param {Array} _fileList 文件列表
     */
        onFileSuccess(_response, _file, _fileList) {
            console.log(_response, _file, _fileList)
            if (_response.msg === '成功') {
                this.encLosureList.push({
                    name: _response.data.sourceName,
                    url: _response.data.fileSourceId
                })
            } else {
                this.$message.error(_response.msg || '上传失败')
            }
        },

        /**
     * @description: 上传失败
     */
        onFileError() {
            this.$message.error('上传失败')
        },

        /**
     * @description: 移除文件
     * @param {Object} _file 移除的文件信息
     * @param {Array} _fileList 文件列表
     */
        onFileRemove(_file, _fileList) {
            console.log(_file, _fileList)
            this.encLosureList = _fileList
        },

        /**
     * @description: 文件导出
     * @param {Object} file 文件信息
     */
        handlePreview(file) {
            window.location.href = `${process.env.VUE_APP_GOLDWIND_BASE_API}/v2/file/download?fileSourceId=${file.url}`
        },

        /**
     * @description: 根据相应的阶段判断指派人信息 和数据是否可选
     * @param {String} _val 阶段ID
     */
        onProduction() {
            this.updateForm.carbonPerson = ''
            this.updateForm.department = ''
            this.uChange()
        },

        /**
     * @description: 根据产品ID获得指派人列表
     */
        async uChange() {
            const _val = this.productId
            try {
                const result = await FeedBack.GetListItemAsync({ id: _val })
                if (result.success) {
                    // const arr = []
                    const data = JSON.parse(JSON.stringify(result.data))
                    this.updateUserList = data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 取消按钮
     */
        updateCancel() {
            this.updateDialogVisible = false
            this.updateForm = {
                nowStage: '',
                carbonPerson: '',
                nowPlaint: '',
                department: ''
            }
        },

        /**
     * @description: 阶段列表
     */
        async getChildStageList() {
            try {
                const result = await FeedBack.GetListChildrenAsync({ type: 'NAME' })
                if (result.success) {
                    const arr = []
                    for (const item of result.data) {
                        if (
                            item.id != '1423154037607493634' &&
              item.id != '1423154076169924610' &&
              item.id != '1423154128091213825' &&
              item.id != '1455008058845532161'
                        ) {
                            arr.push(item)
                        }
                    }
                    this.childStageList = arr
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 弹出框传入子组件的更改
     * @param {Boolean} val 弹出框显示或者隐藏的bool值
     */
        updateChange(val) {
            this.updateDialogVisible = val
            this.updateForm = {
                nowStage: '',
                carbonPerson: '',
                nowPlaint: '',
                department: ''
            }
        },

        /**
     * @description: 更新数据解析
     * @param {Object} row 数据信息
     * @param {Sting} stageID 阶段ID
     * @param {Sting} trueID 详情ID
     */
        updateRow(row, stageID, trueID, userid) {
            this.tableItemsID = trueID
            const isDetails = this.$route.path == '/Details'
            let assignedUserId = ''
            let creatorId = ''
            if (isDetails) {
                assignedUserId = row.userId ? row.userId : ''
                creatorId = row.creator ? row.creator : ''
            } else {
                assignedUserId = row.assignedUserId ? row.assignedUserId : ''
                creatorId = row.creatorId ? row.creatorId : ''
            }
            if (row.c1Status === 'C1已关闭' || row.c1Status === true) {
                this.isShow = false
            } else if (userid == assignedUserId && userid == creatorId) {
                this.isShow = true
            } else if (userid != assignedUserId && userid == creatorId) {
                this.isShow = false
            } else {
                this.isShow = true
            }
            this.updateDialogVisible = true
            this.updateForm.nowStage = stageID
            // if (assignedUserId) {
            this.updateForm.carbonPerson = assignedUserId
            // this.updateForm.department = row.creatorDepartment
            this.carbonPersonChange(assignedUserId)
            // }
        },

        /**
     * @description: 根据产品ID获得指派人列表
     * @param {String} _val 产品ID
     */
        async updateProductionChange(_val) {
            try {
                const result = await FeedBack.GetListItemAsync({ id: _val })
                if (result.success) {
                    this.updateUserList = result.data
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 确认按钮
     */
        confirmUpdate(formName) {
            // let objParmars = {}
            let fileUrl = null
            if (this.encLosureList != [] && this.encLosureList.length > 0) {
                const arr = []
                for (const item of this.encLosureList) {
                    if (item.status) {
                        arr.push({
                            name: item.name,
                            url: item.url
                        })
                    } else {
                        arr.push(item)
                    }
                }
                const strs = JSON.stringify(arr)
                fileUrl = strs.substring(1, strs.length - 1)
            }
            // if (this.isShow) {
            //     objParmars = {
            //         id: this.tableItemsID,
            //         operationType: 2,
            //         stage: this.updateForm.nowStage,
            //         userId: this.updateForm.carbonPerson,
            //         content: this.updateForm.nowPlaint,
            //         fileUrl: fileUrl
            //     }
            // } else {
            const objParmars = {
                id: this.tableItemsID,
                operationType: 8,
                stage: null,
                userId: null,
                content: this.updateForm.nowPlaint,
                fileUrl: fileUrl
            }
            // }

            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.updateOptionAsync(objParmars)
                } else {
                    this.$message.error('请检查表单信息是否填写完整')
                    return false
                }
            })
        },

        /**
     * @description: 更新进度
     * @param {Object} parmars 传参
     */
        async updateOptionAsync(parmars) {
            try {
                const result = await FeedBack.OperationAsync(parmars)
                if (result.success) {
                    this.$message.success(result.message)
                    this.updateDialogVisible = false
                    this.updateForm = {
                        nowStage: '',
                        carbonPerson: '',
                        nowPlaint: '',
                        department: ''
                    }
                    this.$emit('refreshPage')
                } else {
                    this.updateDialogVisible = false
                    this.updateForm = {
                        nowStage: '',
                        carbonPerson: '',
                        nowPlaint: '',
                        department: ''
                    }
                    this.$message.error(result.message)
                }
            } catch (error) {
                this.$message.error('服务器异常')
            }
        },

        /**
     * @description: 获取指派人部门
     * @param {String} _val 指派人id
     */
        carbonPersonChange(_val) {
            this.updateUserList.forEach(item => {
                if (item.id == _val) {
                    this.updateForm.department = item.department
                }
            })
        },
        getUpdateContent(Value) {
            this.updateForm.nowPlaint = Value
        }
    }
}
</script>

